package com.ics.cmsadmin.modules.basic.controller;


import com.ics.cmsadmin.frame.core.annotation.Authorize;
import com.ics.cmsadmin.frame.core.bean.ApiResponse;
import com.ics.cmsadmin.frame.core.bean.PageBean;
import com.ics.cmsadmin.frame.core.enums.AuthorizeEnum;
import com.ics.cmsadmin.modules.basic.bean.PictureBean;
import com.ics.cmsadmin.modules.basic.service.PictureService;
import com.ics.cmsadmin.modules.system.service.UploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(value = "图片管理接口")
@RestController
@RequestMapping("/picture")
public class PicturesController {

    @Autowired
    private PictureService pictureService;

    @Autowired
    private UploadService uploadService;

    @Authorize(AuthorizeEnum.PICTURE_QUERY)
    @ApiOperation(value = "分页查询图片列表")
    @PostMapping("/list/{pageNo}/{pageSize}")
    public ApiResponse list(@RequestBody PictureBean t,
                            @ApiParam("页码") @PathVariable int pageNo,
                            @ApiParam("每页条数") @PathVariable int pageSize) {
        PageBean page = new PageBean(pageNo, pageSize);
        return ApiResponse.getDefaultResponse(pictureService.list(t, page));
    }


    @ApiOperation(value = "新增一条图片信息")
    @Authorize(AuthorizeEnum.PICTURE_INSERT)
    @PostMapping("/insert")
    public ApiResponse insert(@RequestBody PictureBean t) {
        t.setId(null);
        return ApiResponse.getDefaultResponse(pictureService.save(t));
    }

    @ApiOperation(value = "更新一条图片信息")
    @Authorize(AuthorizeEnum.PICTURE_UPDATE)
    @PostMapping("/update/{id}")
    public ApiResponse update(@PathVariable Long id, @RequestBody PictureBean t) {
        t.setId(id);
        return ApiResponse.getDefaultResponse(pictureService.save(t));
    }


    @Authorize(AuthorizeEnum.PICTURE_DELETE)
    @ApiOperation(value = "删除一张图片数据")
    @PostMapping("/delete/{id}")
    public ApiResponse delete(@PathVariable Long id) {
        PictureBean picture = pictureService.queryById(id);
        boolean b = pictureService.delete(id);
        if (b) {
            uploadService.deleteUploadedImageByUrl(picture.getPicUrl());
        }
        return ApiResponse.getDefaultResponse(b);
    }
}
